<template>
    <el-form ref="ruleFormRef" style="width: 100%" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon >
        <el-form-item label="班组名称" prop="name">
            <el-input v-model="ruleForm.name" />
        </el-form-item>

        <el-form-item label="权限设置" prop="mobile">
            <el-tree ref="treeRef" style="max-width: 600px" :data="data" :default-checked-keys="checkedKeys" show-checkbox node-key="id" :props="defaultProps"/>
        </el-form-item>

        <el-form-item label="是否启用" prop="status">
            <el-switch v-model="ruleForm.status" />
        </el-form-item>
       
    </el-form>
    <el-divider />
    <div class="text-center">
        <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="loading"> 保存 </el-button>
    </div>
</template>
  
<script lang="ts" setup>
import { reactive, ref,watch } from 'vue'
import { ElMessage, type ComponentSize, type ElTree, type FormInstance, type FormRules } from 'element-plus'
import router from '../../../../router';
import http from '../../../../util/request';

let routerList:any = router.options.routes[0].children
let data:any = ref([])


const loading = ref<boolean>(false)
const checkedKeys:any = ref([])
const treeRef = ref<InstanceType<typeof ElTree>>()
const defaultProps = {
    children: 'children',
    label: 'label',
}

interface RuleForm {
    id:number
    name: string
    status:boolean
    auth:string[]
    type:number
}

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<RuleForm>({
    id:0,
    name: '',
    auth:[],
    status:true,
    type:1
})

const onGetRouter = () => {
    data.value = []
    routerList.forEach((e:any)=>{
        if(e.children){
            e.children = e.children.filter((item:any) => item.meta.is_show == true )
        }
        if(e.name != 'companys'){
            data.value.push(mapRouter(e))
        }
    })
}

const mapRouter = (rdata:any) => {
    rdata.id = rdata.name
    rdata.label = rdata.meta.side_name
    rdata.children.forEach((element:any) => {
        element.id = element.name
        element.label = element.meta.side_name
        if(element.children){
            mapRouter(element)
        }
    });
    return rdata
}

const onGetData = () => {
    checkedKeys.value = []
    http.get('/role/'+ruleForm.value.id).then((response:any)=>{
        ruleForm.value = response.data.data
        ruleForm.value.auth = ruleForm.value.auth ? JSON.parse(response.data.data.auth) : []
        checkedKeys.value = ruleForm.value.auth
    })
}

const props = defineProps<{
    data:number,
    type:number
}>()

watch(props,()=>{
    onGetRouter()
    ruleForm.value.id = props.data
    ruleForm.value.type = props.type
    ruleForm.value.name = ''
    ruleForm.value.status = true
    ruleForm.value.auth = []
    checkedKeys.value = []
    if(ruleForm.value.id){
        onGetData()
    }
},{ immediate: true })

const rules = reactive<FormRules<RuleForm>>({
    name: [
        { required: true, message: '请输入名称', trigger: 'blur' },
        { min: 2, max: 30, message: '范围在2-30字之间', trigger: 'blur' },
    ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    let auth:any = treeRef.value!.getCheckedKeys(false)
    let authHal:any = treeRef.value!.getHalfCheckedKeys()
    ruleForm.value.auth = auth
    ruleForm.value.auth.push(...authHal)
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            loading.value = true
            let request:any = null
            if(ruleForm.value.id){
                request = http.patch('/role',ruleForm.value)
            }else{
                request = http.put('/role',ruleForm.value)
            }
            request.then((response:any)=>{
                loading.value = false
                if(response.data.code != 200){
                    ElMessage.error(response.data.msg);
                    return
                }
                onSave()
            })
            
        } else {
            console.log('error submit!', fields)
        }
    })
}


const onSave = () => {
    emit('onSave')
}

const emit = defineEmits(['onSave'])
</script>
<style scoped>
</style>
